import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    //模拟实现一个UDP回显客户端；
    private DatagramSocket socket=null;
    public String severIP;
    public int severPort;
    public UdpEchoClient(String severIP,int severPort) throws SocketException {
        this.severIP=severIP;
        this.severPort=severPort;
        socket=new DatagramSocket();
    }
    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while(true){
            System.out.println("请输入你要发送的请求");
            if(!scanner.hasNext()){
                break;
            }
            String request=scanner.next();
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
            InetAddress.getByName(severIP),severPort);
            socket.send(requestPacket);
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }

}
